package com.jackson.sprintredis.redissonExample;

/*
 * Author: JacksonCoder
 * FileName: RedisService
 * Version: 1.0.0
 * Date: 2025/6/14
 */

import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedissonClient redissonClient;

    // 字符串操作
    public void setString(String key, String value) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    public String getString(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    // 分布式锁示例
    public void distributedLockExample() {
        RLock lock = redissonClient.getLock("myLock");
        try {
            // 尝试加锁，最多等待100秒， 锁持有时间30秒
            boolean isLocked = lock.tryLock(100, 30, TimeUnit.SECONDS);
            if (isLocked) {
                try {
                    // 业务逻辑
                    System.out.println("获取到锁，执行任务...");
                } finally {
                    lock.unlock(); // 释放锁
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}


